# gui/worker_threads.py
"""
后台工作线程 - 用于聊天功能
注意:仿真功能已迁移到多进程架构(simulator/simulation_process.py)
"""

import traceback
from PyQt5.QtCore import QThread, pyqtSignal, QObject


class ChatWorker(QThread):
    """聊天处理工作线程"""

    # 信号定义
    message_processed = pyqtSignal(str)  # 消息处理完成
    processing_error = pyqtSignal(str)   # 处理错误
    progress_updated = pyqtSignal(str)   # 状态更新

    def __init__(self, chat_agent):
        super().__init__()
        self.chat_agent = chat_agent
        self.message_queue = []
        self.is_processing = False

    def process_message(self, message: str):
        """处理聊天消息"""
        self.message_queue.append(message)
        if not self.is_processing:
            self.start()

    def run(self):
        """线程主循环"""
        self.is_processing = True

        try:
            while self.message_queue:
                message = self.message_queue.pop(0)

                self.progress_updated.emit("正在处理指令...")

                # 处理消息
                response = self.chat_agent.process_message(message)

                # 发送结果
                self.message_processed.emit(response)

        except Exception as e:
            error_msg = f"消息处理错误: {str(e)}"
            self.processing_error.emit(error_msg)
            print(f"聊天处理线程错误: {e}")
            traceback.print_exc()
        finally:
            self.is_processing = False


class WorkerThreadManager(QObject):
    """工作线程管理器 - 仅用于聊天功能

    注意:仿真相关的线程已废弃,请使用SimulationProcess(多进程架构)
    """

    # 统一状态信号
    status_updated = pyqtSignal(str, str)  # (类型, 状态消息)

    def __init__(self, radar_engine=None, signal_processor=None, chat_agent=None):
        super().__init__()

        # radar_engine和signal_processor参数保留以兼容现有代码,但不再使用
        # 创建聊天工作线程
        self.chat_worker = ChatWorker(chat_agent) if chat_agent else None

        # 连接信号
        if self.chat_worker:
            self.chat_worker.progress_updated.connect(self._on_chat_progress)
            self.chat_worker.processing_error.connect(self._on_chat_error)

    def _on_chat_progress(self, status):
        """聊天处理进度回调"""
        self.status_updated.emit("chat", status)

    def _on_chat_error(self, error):
        """聊天处理错误回调"""
        self.status_updated.emit("error", f"消息处理错误: {error}")

    def stop_all_workers(self):
        """停止所有工作线程"""
        if self.chat_worker and self.chat_worker.isRunning():
            self.chat_worker.terminate()
            self.chat_worker.wait()
